package cn.edu.ntu.utils;

import static java.lang.System.out;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class HttpUtils {

	static final int STATUS_SUCCESS = 200;
	
    static CloseableHttpClient httpclient = null;
    static RequestConfig requestConfig = null;

    static {
         requestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.BEST_MATCH).build();
         httpclient = HttpClients.custom().setDefaultRequestConfig(requestConfig).build();
    }

    public static String doGet(String url, String cookieVal) {
        RequestConfig requestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.BEST_MATCH).build();
         CloseableHttpClient   httpclient = HttpClients.custom().setDefaultRequestConfig(requestConfig).build();
        try {  
           // 创建httpget.    
           HttpGet httpget = new HttpGet(url);
           httpget.addHeader("Cookie", cookieVal);
           httpget.addHeader("Accept-Encoding","gzip, deflate");
           httpget.addHeader("Accept-Language","zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3");
           httpget.addHeader("Cache-Control","no-cache");
           httpget.addHeader("Connection","keep-alive");
           httpget.addHeader("Content-Type","application/json; charset=UTF-8");
           httpget.addHeader("Referer","http://www.zhihu.com/");
           httpget.addHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36");
           System.out.println("executing request " + httpget.getURI());  
           // 执行get请求.    
           CloseableHttpResponse response = httpclient.execute(httpget); 
           try {  
               // 获取响应实体    
               HttpEntity entity = response.getEntity();  
               System.out.println("--------------------------------------");  
               // 打印响应状态    
               System.out.println(response.getStatusLine());  
               if (entity != null) {  
            	   String string = EntityUtils.toString(entity);
               	   System.out.println(string);
                   return string;
               }  
               System.out.println("------------------------------------");  
           } finally {  
               response.close();  
           }  
       } catch (ClientProtocolException e) {  
           e.printStackTrace();  
       } catch (ParseException e) {  
           e.printStackTrace();  
       } catch (IOException e) {  
           e.printStackTrace();  
       } 
        return null;
    }


    /**以utf-8形式读取*/
    public static String doPost(String url,List<NameValuePair> formparams) {
        return doPost(url, formparams,"UTF-8");
    }

    public static String doPost(String url,List<NameValuePair> formparams,String charset) {
         RequestConfig requestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.BEST_MATCH).build();
         CloseableHttpClient httpclient = HttpClients.custom().setDefaultRequestConfig(requestConfig).build();
        // 创建默认的httpClient实例.    
        // CloseableHttpClient httpclient = HttpClients.createDefault(); 
        // 创建httppost    
        HttpPost httppost = new HttpPost(url); 
        httppost.addHeader("Cookie", "xxxxxxx");
        httppost.addHeader("Accept-Encoding","gzip, deflate");
        httppost.addHeader("Accept-Language","zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3");
        httppost.addHeader("Cache-Control","no-cache");
        httppost.addHeader("Connection","keep-alive");
        httppost.addHeader("Content-Type","application/x-www-form-urlencoded"); //application/json; charset=UTF-8
        httppost.addHeader("Referer","http://www.zhihu.com/");
        httppost.addHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36");


        UrlEncodedFormEntity uefEntity;
        try {
            uefEntity = new UrlEncodedFormEntity(formparams, charset);
            httppost.setEntity(uefEntity);
            CloseableHttpResponse response = httpclient.execute(httppost);
            try {
                // 打印响应状态    
                System.out.println(response.getStatusLine());
                if(STATUS_SUCCESS == response.getStatusLine().getStatusCode()){
                	String cookieVal = response.getFirstHeader("Set-Cookie").getValue();
                	System.out.format("cookie：{0}", cookieVal);
                	return cookieVal;
                }else{
                	HttpEntity entity = response.getEntity(); 
                    if (entity != null) {  
                    	String string = EntityUtils.toString(entity);
                    	System.out.format("返回数据：{0}", string);
                        return string;
                    }  
                }
            } finally {  
                response.close();  
            }  
        } catch (ClientProtocolException e) {  
            e.printStackTrace();  
        } catch (UnsupportedEncodingException e1) {  
            e1.printStackTrace();  
        } catch (IOException e) {  
            e.printStackTrace();  
        } 
        return null;
    }
	
    public static void main(String[] args) {
//        String content = HttpUtils.doGet("https://www.zhihu.com/");
//    	List<NameValuePair> paramsList = new ArrayList<NameValuePair>();
//    	paramsList.add(new BasicNameValuePair("phone", "17723507130"));
//    	paramsList.add(new BasicNameValuePair("password", "e10adc3949ba59abbe56e057f20f883e"));
//        String cookieVal = HttpUtils.doPost("http://shop.luruiqi.cc/login", paramsList);
//        HttpUtils.doGet("http://shop.luruiqi.cc/user/userInfo", cookieVal);
    	
    	out.println("helloworld");
    }
    
}
